from unsloth import FastLanguageModel

import torch # 如果pytorch安装成功即可导入pip
print("--------------- pytorch version -----------------")
print(torch.cuda.is_available()) # 查看CUDA是否可用
print(torch.cuda.device_count()) # 查看可用的CUDA数量
print(torch.version.cuda) # 查看CUDA的版本号
print("--------------------------------------------------")

max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.


''' Data Prep '''
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
{}

### Input:
{}

### Response:
{}"""


''' Now if you want to load the LoRA adapters we just saved for inference, set False to True: '''
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "/mnt/g/LLM/lover_llama/scripts/training/unsloth/QuantMerge", # YOUR MODEL YOU USED FOR TRAINING
    max_seq_length = max_seq_length,
    dtype = dtype,
    load_in_4bit = load_in_4bit,
)
FastLanguageModel.for_inference(model) # Unsloth has 2x faster inference!

# alpaca_prompt = You MUST copy from above!
FastLanguageModel.for_inference(model) # Unsloth has 2x faster inference!
inputs = tokenizer(
[
    alpaca_prompt.format(
        "What is a famous tall tower in Paris?", # instruction
        "", # input
        "", # output - leave this blank for generation!
    )
], return_tensors = "pt").to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 64)



''' GGUF / llama.cpp Conversion '''
# Save to 8bit Q8_0
if True: model.save_pretrained_gguf("GGUF", tokenizer,)
if False: model.push_to_hub_gguf("hf/GGUF", tokenizer, token = "")

# Save to 16bit GGUF
if False: model.save_pretrained_gguf("GGUF", tokenizer, quantization_method = "f16")
if False: model.push_to_hub_gguf("hf/GGUF", tokenizer, quantization_method = "f16", token = "")

# Save to q4_k_m GGUF
if False: model.save_pretrained_gguf("GGUF", tokenizer, quantization_method = "q4_k_m")
if False: model.push_to_hub_gguf("hf/GGUF", tokenizer, quantization_method = "q4_k_m", token = "")


